package com.ming.config;

import com.ming.filter.JwtAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * 简化的Spring Security配置类
 * 专门解决登录接口被拦截的问题
 *
 * @author ming
 * @version 2.0
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Autowired
    private JwtAuthenticationFilter jwtAuthenticationFilter;

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        // 禁用CSRF（因为使用JWT）
        http.csrf(AbstractHttpConfigurer::disable);

        // 配置无状态会话管理
        http.sessionManagement(session -> session.sessionCreationPolicy(org.springframework.security.config.http.SessionCreationPolicy.STATELESS));

        // 添加JWT过滤器
        http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

        // 简化配置 - 使用字符串匹配而不是RequestMatchers
        http.authorizeHttpRequests(authz -> authz
                // 放行所有OPTIONS请求
                .requestMatchers(request -> request.getMethod().equals("OPTIONS")).permitAll()
                // 放行登录接口
                .requestMatchers("/emps/login").permitAll()
                // 放行错误页面
                .requestMatchers("/error").permitAll()
                // 放行健康检查
                .requestMatchers("/actuator/**").permitAll()
                // 放行Swagger相关
                .requestMatchers("/swagger-ui/**").permitAll()
                .requestMatchers("/v3/api-docs/**").permitAll()
                .requestMatchers("/swagger-resources/**").permitAll()
                .requestMatchers("/webjars/**").permitAll()
                .requestMatchers("/files/**").permitAll()
                // 其他所有请求都需要认证
                .anyRequest().authenticated()
        );

        return http.build();
    }
}